package com.rrd.dw.mr.all;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil;
import org.apache.hadoop.hbase.mapreduce.TableMapper;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.MultipleOutputs;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

import com.rrd.dw.utils.DateUtil;
import com.rrd.dw.utils.HBaseUtil;
import com.rrd.dw.utils.MD5Util;

/**
 * Created by liubaoxin on 2018/05/28.
 */
public class ExportAllAliPayDataToDW extends Configured implements Tool {
	public static final String CRT001 = "\001";
	public static final String[] PAY_COLUMNS = { "account_name", "real_name", "auth_status", "idno", "mobile",
			"register_time:date", "last_login_time:date", "source_user_mobile", "source_user_idno", "source",
			"login_type:int", "alipay_account_type:int", "mess_type" };// pay
	public static final String[] ORDER_COLUMNS = { "amount", "time:date", "order_no", "trade_status", "other_side",
			"trade_name" };// pay

	public static final String[] BCARD_COLUMNS = { "bankcard_no", "open_time:date", "bank_mobile", "cardholder",
			"is_quick_pay" };// pay

	public static final String[] ASSET_COLUMNS = { "yuebaoAmount", "yuebao_income", "zhifubao_amount",
			"zhaocaibao_amount", "huabei_limit", "huabei_used", "huabei_bill" };// assets

	public static final String[] JOB_COLUMNS = { "finished:boolean", "requested:boolean", "successful:boolean",
			"start_time:date", "end_time:date", "system_id", "query", "try_times:int", "type", "message", "code" };// job

	@Override
	public int run(String[] args) throws Exception {
		Properties prop = new Properties();
		try (InputStream is = this.getClass().getClassLoader().getResourceAsStream("hbase.properties");) {
			prop.load(is);
		}

		Job job = Job.getInstance(HBaseConfiguration.create(this.getConf()));
		Configuration conf = job.getConfiguration();
		conf.set("hbase.zookeeper.quorum", prop.get("hbase.zookeeper.quorum").toString());
		conf.set("hbase.rootdir", prop.get("hbase.rootdir").toString());

		conf.set("mapreduce.map.memory.mb", "3072");
		conf.set("mapreduce.reduce.memory.mb", "5120");
		conf.set("hbase.client.scanner.timeout.period", "120");
		conf.set("mapreduce.output.fileoutputformat.compress", "true");
		conf.set("mapreduce.output.fileoutputformat.compress.type", "BLOCK");
		conf.set("mapreduce.output.fileoutputformat.compress.codec", "org.apache.hadoop.io.compress.GzipCodec");
		conf.set("io.compression.codecs", "org.apache.hadoop.io.compress.GzipCodec");
		conf.set("mapreduce.task.io.sort.factor", "10");
		String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
		if (otherArgs.length != 4) {
			System.err.println("Usage: DataExportTool <out> <start_time> <end_time>");
			return -1;
		}
		Long startTime = HBaseUtil.parseDate(otherArgs[1]).getTime();
		Long endTime = HBaseUtil.parseDate(otherArgs[2]).getTime();
		String model = otherArgs[3];
		job.setJarByClass(ExportAllAliPayDataToDW.class);
		List<Scan> scans = new ArrayList<>();

		Scan scan = new Scan();
		scan.setCacheBlocks(false);
		scan.setCaching(200);
		scan.setMaxVersions(1);
		scan.setAttribute(Scan.SCAN_ATTRIBUTES_TABLE_NAME, Bytes.toBytes("alipay_records"));
		if (!model.equals("ALL")) {
			System.out.println("增量运行.............");
			scan.setTimeRange(startTime, endTime + 14400000);
		} else {
			System.out.println("全量运行.............");

		}

		scans.add(scan);

		TableMapReduceUtil.initTableMapperJob(scans, ExportAliPayDataToDWMapper.class, Text.class, Text.class, job);
		FileOutputFormat.setOutputPath(job, new Path(otherArgs[0]));
		MultipleOutputs.addNamedOutput(job, "basepayinfo", TextOutputFormat.class, Text.class, Text.class);
		MultipleOutputs.addNamedOutput(job, "orderlist", TextOutputFormat.class, Text.class, Text.class);
		MultipleOutputs.addNamedOutput(job, "bcardlist", TextOutputFormat.class, Text.class, Text.class);

		job.setReducerClass(ExportAliPayDataToDWReducer.class);
		job.setNumReduceTasks(5);
		return job.waitForCompletion(true) ? 0 : 1;

	}

	public static void main(String[] args) throws Exception {
		Configuration conf = HBaseConfiguration.create();
		int res = ToolRunner.run(conf, new ExportAllAliPayDataToDW(), args);
		System.exit(res);
	}

	public static class ExportAliPayDataToDWMapper extends TableMapper<Text, Text> {
		private Text k = new Text();
		private Text v= new Text();
		private String user_id = null;
		private String jobid = null;
		private String timestampstr = "";
		private Cell dataCell = null;
		private Cell countCell = null;
		private String type = "";
		private String field = "";
		private String accountName = null;
		private StringBuffer sb = new StringBuffer("");
	
		@Override
		protected void map(ImmutableBytesWritable key, Result value, Context context)
				throws IOException, InterruptedException {
			Thread.sleep(20);
			sb.delete(0, sb.length());
			Object[] rowkey = HBaseUtil.decodeRowkey(key.get());
			if (rowkey == null) {
				return;
			}
			dataCell = value.getColumnLatestCell(Bytes.toBytes("job"), Bytes.toBytes("start_time"));
			if(dataCell ==null ){
				timestampstr = "2017-01-01 00:00:00";
			}else{
				timestampstr = DateUtil.formateDateStr(new Date((Long)HBaseUtil.getValue("long", CellUtil.cloneValue(dataCell))));
			}
			 
			jobid = rowkey[1].toString();
			dataCell = value.getColumnLatestCell(Bytes.toBytes("pay"), Bytes.toBytes("account_name"));
			accountName = dataCell == null ? "" : HBaseUtil.getValue(CellUtil.cloneValue(dataCell)).toString();
//			user_id = MD5Util.getMd5(timestampstr+jobid+(accountName==null?"":accountName));
			sb.append(timestampstr).append(CRT001).append(jobid).append(CRT001);
			// pay基本信息
			for (String str1 : PAY_COLUMNS) {
				String[] fieldArray = str1.split(":");
				if (fieldArray.length > 1) {
					field = fieldArray[0];
					type = fieldArray[1];
				} else {
					field = fieldArray[0];
					type = "string";
				}
				dataCell = value.getColumnLatestCell(Bytes.toBytes("pay"), Bytes.toBytes(field));
				sb.append(dataCell == null ? "" : HBaseUtil.getValue(type, CellUtil.cloneValue(dataCell)))
						.append(CRT001);
			}
			// asset信息
			for (String str1 : ASSET_COLUMNS) {
				String[] fieldArray = str1.split(":");
				if (fieldArray.length > 1) {
					field = fieldArray[0];
					type = fieldArray[1];
				} else {
					field = fieldArray[0];
					type = "string";
				}
				dataCell = value.getColumnLatestCell(Bytes.toBytes("assets"), Bytes.toBytes(field));
				sb.append(dataCell == null ? "" : HBaseUtil.getValue(type, CellUtil.cloneValue(dataCell)))
				.append(CRT001);
			}
			// job信息
			for (String str1 : JOB_COLUMNS) {
				String[] fieldArray = str1.split(":");
				if (fieldArray.length > 1) {
					field = fieldArray[0];
					type = fieldArray[1];
				} else {
					field = fieldArray[0];
					type = "string";
				}
				dataCell = value.getColumnLatestCell(Bytes.toBytes("job"), Bytes.toBytes(field));
				sb.append(dataCell == null ? "" : HBaseUtil.getValue(type, CellUtil.cloneValue(dataCell)))
				.append(CRT001);
			}
			k.set("job"+user_id);
			v.set(sb.substring(0, sb.length()-1).replace("\n", " "));
			context.write(k,v);
			sb.delete(0, sb.length());

			// payorder
			countCell = value.getColumnLatestCell(Bytes.toBytes("pay"), Bytes.toBytes("AliPayOrdercount"));
			if (countCell != null) {
				int count = Bytes.toInt(CellUtil.cloneValue(countCell));
				
				for (int i = 0; i < count; i++) {
					sb.delete(0, sb.length());
					sb.append(this.timestampstr).append(CRT001).append(this.jobid).append(CRT001).append(this.accountName).append(CRT001);
					for (String bstr : ORDER_COLUMNS) {
						String[] fieldArray = bstr.split(":");
						if (fieldArray.length > 1) {
							field = fieldArray[0];
							type = fieldArray[1];
						} else {
							field = fieldArray[0];
							type = "string";
						}
						dataCell = value.getColumnLatestCell(Bytes.toBytes("pay"), Bytes.toBytes(field + "#" + i));
						if (dataCell != null) {
							sb.append(HBaseUtil.getValue(type, CellUtil.cloneValue(dataCell)));
						}
						sb.append(CRT001);
					}
				   v.set( MD5Util.getMd5(sb.toString())+CRT001+(sb.substring(0, sb.length()-1).replace("\n", "")));
				   k.set("payorder"+user_id);
					context.write(k,v);
					 
				}
			}
			// bankcard
			
		}

	}

	public static class ExportAliPayDataToDWReducer extends Reducer<Text, Text, Text, Text> {
		private MultipleOutputs<Text, Text> mos;
		private String kstr=null;
		@Override
		protected void setup(Context context) throws IOException, InterruptedException {
			this.mos = new MultipleOutputs<>(context);
		}

		@Override
		protected void cleanup(Context context) throws IOException, InterruptedException {
			this.mos.close();
		}

		private NullWritable k = NullWritable.get();

		@Override
		protected void reduce(Text key, Iterable<Text> values, Context context)
				throws IOException, InterruptedException {
			kstr = key.toString();
			for (Text val : values) {
			
				if (kstr.startsWith("job")) {
					this.mos.write("basepayinfo", k, val);
				} else if (kstr.startsWith("payorder")) {
					this.mos.write("orderlist", k, val);
				} else {
					this.mos.write("bcardlist", k, val);
				}
			}

		}
	}
}
